package com.tansun.easycare.rule.scoremodel.web;

import javax.servlet.http.HttpServletRequest;

import com.tansun.easycare.rule.common.enums.RuleModelTypeFileEnum;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.tansun.easycare.core.utils.ResponseTable;
import com.tansun.easycare.rule.common.JsonMessage;
import com.tansun.easycare.rule.common.ResMessage;
import com.tansun.easycare.rule.common.RuleBaseController;
import com.tansun.easycare.rule.common.model.ResponseVO;
import com.tansun.easycare.rule.common.web.model.ProjectInfo;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.model.RuleManageVO;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.easycare.rule.ruleversion.entity.RuleVersioninfo;
import com.tansun.easycare.rule.scoremodel.model.ScoreEntity;
import com.tansun.easycare.rule.scoremodel.service.ScoreModelService;
import com.tansun.easycare.rule.table.singletblindex.model.IndexDetailVO;
import com.tansun.easycare.rule.table.singletblindex.model.RuleTbleManage;
import com.tansun.rule.utils.LoggerManager;

/**
 * 评分模型action
 *
 * @author Lph
 */
@RestController
@RequestMapping(value = "/ruleProj/scoreModel")
public class ScoreCardController extends RuleBaseController {

    @Autowired
    private ScoreModelService scoreModelService;
    @Autowired
    private RuleManageService ruleManageService;

    /**
     * 评分模型列表
     *
     * @param projectCode 项目code
     * @param param       赋值索引模型
     * @return 赋值索引路径
     */
    @RequestMapping("index")
    public ResponseTable<RuleManageVO> index(@RequestBody RuleManageVO param) throws Exception {
        PageInfo<RuleManageVO> pageInfo = this.ruleManageService.findRuleManageVO(param.getPage(), param);
        ResponseTable<RuleManageVO>  resVo  = new  ResponseTable<RuleManageVO>(pageInfo);
        return resVo;
    }

    /**
     * 修改评分模型接口
     * @param projectInfo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "detail")
    public ResponseVO detail(@RequestBody ProjectInfo projectInfo) throws Exception {
    	ResponseVO  res  = new ResponseVO();
        RuleManage indexModel = null;
        if (StringUtils.isEmpty(projectInfo.getManageId())) {
        	indexModel  =  new  RuleManage();
        }else {
            indexModel = this.ruleManageService.getById(projectInfo.getManageId());
            if(indexModel==null){
            	indexModel = ruleManageService.findByCode(projectInfo.getManageId(), projectInfo.getProjectCode());
            }     	
        }    		
        if(StringUtils.isNotEmpty(projectInfo.getVersion())){
        	indexModel.setVersion(projectInfo.getVersion());
        }
        RuleTbleManage  ruleTbl = new  RuleTbleManage();
        ruleTbl.setIsedit(projectInfo.getIsedit());
        ruleTbl.setRankRelationId(projectInfo.getRankRelationId());
        ruleTbl.setRuleManage(indexModel);
        res.setData(ruleTbl);
        return  res;        

    }

    /**
     * 获取评分模型详情
     *
     * @param scoreId 评分模型ID
     * @param version 评分模型版本号（若不传，取最新版）
     * @return 评分模型信息及规则信息
     */
    @RequestMapping(value = "getScoreDetail2")
    public @ResponseBody
    JsonMessage getScoreDetail(HttpServletRequest request, String scoreId, @RequestParam(value = "version", required = false) String version, String temp) throws Exception {
        JsonMessage ret = new JsonMessage();
        try {
            RuleManage scoreModel = this.ruleManageService.getById(scoreId);
            ScoreEntity entity = new ScoreEntity();
            entity.setScoreModel(scoreModel);
//            if (StringUtils.isEmpty(version)) {
//                version = scoreModel.getVersion();
//            }
            if("1".equals(temp)) {
    			version = scoreModel.getActiveVersion();
    		}
            entity.setTreeList(this.scoreModelService.getScoreItems(scoreId, version));
            ret.setData(entity);
        } catch (Exception e) {
            LoggerManager.error(e.getMessage(), e, this.getClass());
            ret.setResult(false);
            ret.setMessage("评分模型信息获取失败，请查看日志");
        }
        return ret;
    }
    /**
     * 获取赋值索引模型详情
     *
     * @param indexId 一维表索引id
     * @param version 版本号
     * @return 一维表索引详情，包含模型信息和规则信息
     */
    @RequestMapping(value = "getScoreDetail")
    public ResponseVO getIndexDetail(@RequestBody IndexDetailVO  indexDetail) throws Exception {
    	ResponseVO ret = new ResponseVO();
        try {
            RuleManage indexModel = this.ruleManageService.getById(indexDetail.getIndexId());
            String  version = indexDetail.getVersion();
            if (StringUtils.isEmpty(version)) version = indexModel.getVersion();
            if("1".equals(indexDetail.getTemp())) {
    			version = indexModel.getActiveVersion();
    		}
//            List<SingleTblIndexRow> indexInfoList = singleTblIndexService.findTblIndexRowList(indexDetail.getIndexId(), version);
            ScoreEntity entity = new ScoreEntity();
            entity.setIndexModel(indexModel);
            entity.setTreeList(this.scoreModelService.getScoreItems(indexDetail.getIndexId(), version));
//            entity.setSingleTblIndexList(indexInfoList);
            RuleVersioninfo ruleVersion = this.ruleManageService.findRuleVersionInfo(indexModel.getProjectCode(), indexModel.getId());
            if (ruleVersion != null) {
            	entity.setDatasetNames(ruleVersion.getDatasetNames());
            }
            ret.setData(entity);
        } catch (Exception e) {
            LoggerManager.error(e.getMessage(), e, this.getClass());
            ret.setStatus(ResponseVO.ERROR);;
            ret.setDescription("赋值索引信息获取失败");
        }
        return ret;
    }

    /**
     * 评分模型弹出框
     *
     * @param projectCode 规则项目编号
     * @return 页面路径
     */
    @RequestMapping(value = "scoreDialog")
    public String scoreDialog(HttpServletRequest request, String projectCode, ModelMap map) throws Exception {
        map.put("projectCode", projectCode);
        return "rule/scoreModel/scoreDialog";
    }

    /**
     * 保存或更新评分模型
     *
     * @param scoreEntity 页面上评分模型的信息（包含模型信息，规则配置信息）
     * @return 是否保存成功，保存异常原因
     */
    @RequestMapping("saveOrUpdate")
    public @ResponseBody ResponseVO saveOrUpdate(@RequestBody ScoreEntity scoreEntity) throws Exception {
    	ResponseVO res = new ResponseVO();
    	res.setStatus(ResponseVO.OK);
        try {
            Integer num = this.ruleManageService.countListFindName(scoreEntity.getScoreModel(), RuleModelTypeFileEnum.ScoreModel.type);
            if (num != null && num>0) {
                res.setStatus(ResponseVO.ERROR);
                res.setDescription("变量名称重复，请使用其他有效名称");
                return res;
            }
            scoreModelService.saveOrUpdate(scoreEntity);
        } catch (Exception e) {
        	String error = ExceptionUtils.getStackTrace(e);
        	logger.error(error);
        	res.setDescription(e.getMessage());
        	res.setDesDetail(error);
        	res.setStatus(ResponseVO.ERROR);
        }
        return res;
    }

    /**
     * 决策表显示java代码
     *
     * @param tableEntity 包含模型及决策表信息
     * @return 返回是否保存成功
     */
    @RequestMapping("showJavaCode")
    public @ResponseBody
    ResponseVO showJavaCode(@RequestBody ScoreEntity scoreEntity) throws Exception {
    	ResponseVO res = new ResponseVO();
    	res.setStatus(ResponseVO.OK);
    	String javacode = scoreModelService.showJavaCode(scoreEntity);
        res.setData(javacode);
        return res;
    }
    
 
    @Override
    public void setRuleBizService() {
        super.setRuleBaseService(this.scoreModelService);
    }
}
